package com.mymall.serve.service;
import java.time.LocalDateTime;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mymall.serve.dto.param.UserAddParam;
import com.mymall.serve.entity.MallUser;
import com.mymall.serve.enums.ResultCodeEnum;
import com.mymall.serve.exception.BusException;
import com.mymall.serve.mapper.MallUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 用户信息service
 *
 * @author weiwei
 * @since 2020-04-11 19:37
 **/
@Slf4j
@Service
public class MallUserService extends ServiceImpl<MallUserMapper, MallUser> {

    /**
     * 根据openId获取用户信息
     *
     * @author weiwei
     * @param openId
     * @date 2020/4/11 22:05
     * @return com.mymall.serve.entity.MallUser
     */
    public MallUser getUserByOpenId(String openId) {
        QueryWrapper<MallUser> wrapper = new QueryWrapper<>();
        wrapper.eq("wx_open_id",openId);
        return this.getOne(wrapper);
    }

    public MallUser getUserByLoginName(String username) {
        QueryWrapper<MallUser> wrapper = new QueryWrapper<>();
        wrapper.eq("entity_name",username);
        return this.getOne(wrapper);
    }

    public boolean getPersonByLoginNameExist(String loginEntry) {
        MallUser userByLoginName = this.getUserByLoginName(loginEntry);
        if (userByLoginName != null){
            return true;
        }
        return false;
    }

    public Long insertUser(UserAddParam sysUserAddParam, Long createrId) {
        boolean isExist = this.getPersonByLoginNameExist(sysUserAddParam.getLoginEntry());
        if (isExist) {
            log.error("新增失败，登录名重复");
            throw new BusException(ResultCodeEnum.ADMIN_USER_NAME_EXIST_ERROR);
        }
        MallUser mallUser = new MallUser();
        mallUser.setPhone(sysUserAddParam.getMobilePhone());
        mallUser.setUserName(sysUserAddParam.getUserName());
        mallUser.setEntityName(sysUserAddParam.getLoginEntry());
        mallUser.setSalt("123");
        mallUser.setPassword(sysUserAddParam.getLoginPwd());
        mallUser.setCreateTime(LocalDateTime.now());
        this.save(mallUser);
        return mallUser.getId();
    }
}
